package cn.tdeu.v2_1;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 *聊天室 Version 2.1
 *客户端基本不变：关闭socket，拓展增加IP
 *                         1.私有化IP
 *                         2.构造器，当前IP进行赋值
 *                         3.任意位置使用IP【读入知道对方IP】
 *
 */
public class Client {
    private Socket socket;
    //1.私有化IP
    private String ip;
    public Client(){
        try {
            socket=new Socket("172.21.69.1",0202);
            //2确定传入IP就是当前IP地址
            ip=socket.getInetAddress().getHostAddress();
        } catch (UnknownHostException e){
            System.out.println("IP地址有问题，请询问服务器端！");
        } catch (IOException e) {
            System.out.println("客户端主动退出了：断开链接");
        }
    }
    //3.创建方法 start()  逻辑  使用IO流 写出
    public void start(){
        PrintWriter pw=null;  //置空流--赋值--关流
        try {
            OutputStream os=socket.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(os,"UTF8");
            BufferedWriter bw=new BufferedWriter(osw);

            pw=new PrintWriter(bw,true);
            System.out.println("客户端用户：请输入文字：");
            Scanner input=new Scanner(System.in);
            while(true){
                String say=input.nextLine();
                pw.println("客户端说"+say);  //
                System.out.println("写出完毕");
            }
        } catch (UnsupportedEncodingException e){
            System.out.println("客户端与服务器端：字符集不一致！");
        } catch (IOException e) {
            System.out.println("客户端断开了链接！");
        } finally {
            //关闭流  关闭socket
            if(pw!=null)
                pw.close();
            if (socket!=null&&!socket.isClosed()){
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("客户端关闭成功~");
                }
                System.out.println("客户端关闭失败~");
            }
        }
        //读入
       /* while(true){
            String str=br.readLine();
            System.out.println("服务器说话："+str);
        }*/
    }

    public static void main(String[] args){
        Client client=new Client();
        client.start();
    }
}
